<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    // 当浏览器支持websocket时
    if(window.WebSocket){
        socket = new WebSocket("ws://localhost:8888/hello");
        // 监听服务器发送的消息
        socket.onmessage = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" +ev.data;
        }
        socket.onopen = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = "连接开启了"
        }

        socket.onclose = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "连接关闭了"
        }
    }

    // 发送消息
    function send(message) {
        // 判断socket是否创建好
        if(!window.socket){
            return;
        }
        if(socket.readyState == WebSocket.OPEN){
            socket.send(message);
        }else {
            alert("连接还未开启");
        }
    }
</script>
    <form onsubmit="return false">
        <textarea name="message" style="width: 300px;height: 300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">
        <textarea id="responseText" style="width: 300px;height: 300px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
    </form>
</body>
</html>
